package cn.monkey.family.server.domain.uc.user;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.Context;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.uc.user.UserDto;
import cn.monkey.family.data.uc.user.UserQueryRequest;
import cn.monkey.family.data.uc.user.role.UserRoleBindRequest;
import com.google.common.base.Strings;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
public class UserController {

    private final IUserService userService;

    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @GetMapping({"{id}", ""})
    public Result<?> get(@Context RequestContext requestContext,
                         @PathVariable(value = "id", required = false) String id,
                         UserQueryRequest queryRequest,
                         @PageableDefault Pageable pageable) {
        if (!Strings.isNullOrEmpty(id)) {
            return this.userService.readById(requestContext, id);
        }
        return this.userService.readPage(requestContext, queryRequest, pageable);
    }



    @PostMapping
    public Result<?> create(@Context RequestContext requestContext,
                            @RequestBody UserDto userDto) {
        return this.userService.create(requestContext, userDto);
    }

    @PutMapping("{id}")
    public Result<?> update(@PathVariable("id") String id,
                            @Context RequestContext requestContext,
                            @RequestBody UserDto userDto) {
        return this.userService.update(requestContext, id, userDto);
    }

    @DeleteMapping("{id}")
    public Result<?> delete(@PathVariable("id") String id,
                            @Context RequestContext requestContext) {
        return this.userService.delete(requestContext, id);
    }

    @GetMapping({"{id}/role", "role"})
    public Result<?> getUserRole(@PathVariable(value = "id", required = false) String id,
                                 @Context RequestContext requestContext,
                                 UserQueryRequest queryRequest,
                                 @PageableDefault Pageable pageable) {
        if (!Strings.isNullOrEmpty(id)) {
            return this.userService.readUserRole(requestContext, id);
        }
        return this.userService.readUserRole(requestContext, queryRequest, pageable);
    }

    @PostMapping({"{id}/role"})
    public Result<?> bindUserRole(@Context RequestContext requestContext,
                                  @PathVariable(value = "id", required = false) String id,
                                  @RequestBody UserRoleBindRequest userRoleBindRequest) {
        return this.userService.bindUserRole(requestContext, id, userRoleBindRequest);
    }
}
